#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <dirent.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/socket.h>

#include "data_type.h"
#include "cube.h"
#include "cube_define.h"
#include "cube_record.h"

#include "mac_label.h"
#include "xKrnl_policydeal.h"

#define MAX_LINE_LEN 1024

static unsigned char Buf[DIGEST_SIZE*32];

int xKrnl_policydeal_init(void * sub_proc,void * para)
{
    int ret;

    return 0;
}

int xKrnl_policydeal_start(void * sub_proc,void * para)
{
    int ret = 0, len = 0, i = 0, j = 0;
    int rc = 0;

    int type,subtype;	
	BYTE local_uuid[DIGEST_SIZE];	
    ret=proc_share_data_getvalue("uuid",local_uuid);
	if(ret<0)
		return ret;
    void * recv_msg;

    while(1)
    {
        usleep(time_val.tv_usec);

		ret=ex_module_recvmsg(sub_proc,&recv_msg);
		if(ret<0)
			continue;
		if(recv_msg==NULL)
			continue;
		type=message_get_type(recv_msg);
		subtype=message_get_subtype(recv_msg);
		if(!memdb_find_recordtype(type,subtype))
		{
			printf("message format (%d %d) is not registered!\n",
			message_get_type(recv_msg),message_get_subtype(recv_msg));
			continue;
		}
		else if((type==TYPE(MAC_LABEL))&&(subtype==SUBTYPE(MAC_LABEL,FILE_EVENT)))
		{
			ret=proc_deal_audit(sub_proc,recv_msg);
		}
	}
    return 0;
}

int proc_deal_audit(void * sub_proc,void * recv_msg)
{
    int ret;
    int i=0;
	RECORD(MAC_LABEL,FILE_EVENT) * audit_record;
	RECORD(MAC_LABEL,SUBJECT) * subject_label;
	RECORD(MAC_LABEL,OBJECT) * object_label;
    BYTE * digest[DIGEST_SIZE];
    void * send_msg;
    DB_RECORD * db_record;

    send_msg = message_create(TYPE_PAIR(MAC_LABEL,OBJECT),recv_msg); 
    if(send_msg == NULL)
        return -EINVAL;

    do{
        ret = message_get_record(recv_msg,&audit_record,i++);
        if(ret<0)
            return -EINVAL;
        if(audit_record==NULL)
            break;

        object_label=Talloc0(sizeof(*object_label));    
        // Add  your audir deal code here 
        
        calculate_sm3(audit_record->fileName,object_label->object_uuid);
        
	    db_record = memdb_find_first(TYPE_PAIR(MAC_LABEL,SUBJECT),"user_id",&audit_record->uid);
        if(db_record==NULL)
            continue;
        subject_label=db_record->record;
        if(subject_label==NULL)
            continue;
        
        Memcpy(&object_label->label,&subject_label->label,sizeof(RECORD(MAC_LABEL,LABEL)));

        
        message_add_record(send_msg,object_label);

    }while(1);       

     ex_module_sendmsg(sub_proc,send_msg);

    return 0; 
}
